package com.fxcalibre.fxml.control;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;

import com.fxcalibre.db.beans.MediaItem;
import com.fxcalibre.fxml.view.FXMLViewLoader;
import com.fxcalibre.hibernate.dao.MediaItemsDAO;

public class SelectSerie extends VBox
{
	@FXML
	TableView<MediaItem> seriesTable;
	@FXML
	private TableColumn<MediaItem, String> nameColumn;
	ObservableList<MediaItem> tableData = FXCollections.observableArrayList(MediaItemsDAO.getSeries());

	MediaItem selectedSerie;
	Stage dialogStage;

	public SelectSerie()
	{
		FXMLViewLoader.load(this, "SelectSerie.fxml");

		seriesTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
		seriesTable.setItems(tableData);
		nameColumn.setCellValueFactory(new PropertyValueFactory<MediaItem, String>("name"));

		// Listen for selection changes
		seriesTable.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<MediaItem>()
		{
			@Override
			public void changed(ObservableValue<? extends MediaItem> observable, MediaItem oldValue, MediaItem newValue)
			{
				selectedSerie = newValue;
			}
		});
	}

	public MediaItem getSelectedSerie()
	{
		return selectedSerie;
	}

	public void setSelectedSerie(MediaItem selectedSerie)
	{
		this.selectedSerie = selectedSerie;
	}

	@FXML
	protected void selectAndClose(ActionEvent event)
	{
		dialogStage.close();
	}

	public void showInStage()
	{
		dialogStage = new Stage();
		dialogStage.setTitle("Edit Media");
		dialogStage.initModality(Modality.APPLICATION_MODAL);
		Scene scene = new Scene(this);
		dialogStage.setScene(scene);
		dialogStage.sizeToScene();
		dialogStage.showAndWait();
	}

}
